<?php
namespace backend\base;
use Yii;
use base\YiiMobo;
use yii\data\Pagination;

/**
 * Site controller
 */
class BaseBackendController extends \base\BaseController
{
   //public $defaultAction = 'index2';
   
   public $layout = false;
   
   /**
   * 操作跳转类。
   * author xiongyouliang
   */
   public function OperTips($params = null){
	   $data = $params ? $params : ['backurl' => $_SERVER['HTTP_REFERER']];
	   if(!is_array($data)){
		   $data = [];
		   $data['backurl'] = $params;
	   }
	   $rootpath = dirname(Yii::getAlias('@web'));
	   if (!$data['backurl']) $data['backurl'] = $_SERVER['HTTP_REFERER'];
	   $data['backurl'] = substr($data['backurl'], 0, strlen($rootpath)) == $rootpath || preg_match("/^http(|s):\/\//", $data['backurl']) ? $data['backurl'] : Yii::$app->urlManager->createUrl($data['backurl']);
	   echo $this->render('//_system/_opertips', ['data'=> $data]);
	   exit;
   }
   
   
	public function pageView($viewfile = 'index', $params = []){
		$param = isset($params['param']) ? $params['param'] : [];
		$sql = $params['sql'];
		$order = isset($params['order']) ? $params['order'] : '';

		$sqlcount = preg_replace("/^SELECT(.*)FROM/i", "SELECT count(*) FROM", $sql);
		$pageparam = array_merge([
            'totalCount'=> Yii::$app->db->createCommand($sqlcount)->queryScalar(),
			'PageSize' => 20,
        ], isset($params['pageparam']) ? $params['pageparam'] : []);
   
		$pages = new Pagination($pageparam);
        $models = Yii::$app->db->createCommand($sql. ' ' .$order." limit ".$pages->limit." offset ".$pages->offset."")->queryAll();

    	//ajax请求
		if (Yii::$app->request->getIsAjax()){
			$rows['results'] = $models;
		    $rows['counts'] = (int)$pageparam['totalCount'];
			$rows['pagesize'] = $pageparam['PageSize'];
		    $rows['pagecount'] = (int)ceil($rows['counts']/$pageparam['PageSize']);
			if ($_GET['page'] > $rows['pagecount'] || $rows['counts'] == 0){
				$rows['page'] = $_GET['page'];
				$rows['results'] = array();
			}else{
				$rows['page'] = $_GET['page'] >$rows['pagecount'] && $rows['pagecount']>0 ? $rows['pagecount'] : $_GET['page'];
			}
			$rows = array_merge($rows, $param);
			self::echojson($rows);
		}
		//非ajax请求
		$return = [
		    'models' => $models,
            'pages' => $pages,
		];
		
		$return = array_merge($return, $param);
		if ($viewfile){
			return $this->render($viewfile, $return);
		}else{
		    return $return;
		}
	}
	
	
	public function formSave($model, $params = [], $saveCallback = null)
	{
		if ($model->load(Yii::$app->request->post()))
		{
			if($model->save())
            {
				if ($saveCallback){
				    $saveCallback($model);
				}
				if (Yii::$app->request->getIsAjax()){
					self::echojson();
				}else{
			        $this->OperTips($this->getUniqueId().'/index');
				}
			}
		}
     	return $this->render('_form',array_merge(['model'=>$model], $params));
	}
	
	
	public function formBatch($model, $callback = null)
	{
		$primaryKey = $model->primaryKey()[0];
        $ids = isset($_POST['checked_'.$primaryKey.'']) ? $_POST['checked_'.$primaryKey.''] : NULL;
        if ($ids){
            if (isset($_POST['batch_delete'])){
                $model->deleteAll([$primaryKey=>$ids]);
            }
        }else if(isset($_POST['batch_listorder'])){
			if ($_POST['listorder']) foreach($_POST['listorder'] as $id=>$listorder){
				$model->updateAll(['listorder'=>intval($listorder)], [$primaryKey => $id]);
			}
		}
        $callback && $callback($ids);
		$this->OperTips($this->getUniqueId().'/index');
	}
	
   /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }
}
